const { ipcRenderer } = require('electron')

// 页面加载时检查是否有保存的值
window.onload = function() {
    const savedAppCode = localStorage.getItem('appCode')
    const savedUrl = localStorage.getItem('url')
    const rememberChecked = localStorage.getItem('remember') !== 'false'

    if (savedAppCode) {
        document.getElementById('appCode').value = savedAppCode
    }
    if (savedUrl) {
        document.getElementById('url').value = savedUrl
    }
    document.getElementById('remember').checked = rememberChecked
}

// 处理URL格式
function formatUrl(url) {
    try {
        const urlObj = new URL(url)
        // 如果URL不以/结尾，添加/
        if (!urlObj.pathname.endsWith('/')) {
            urlObj.pathname = urlObj.pathname + '/'
        }
        return urlObj.toString()
    } catch (e) {
        throw new Error('无效的URL格式')
    }
}

function navigate() {
    const appCode = document.getElementById('appCode').value
    let url = document.getElementById('url').value
    const remember = document.getElementById('remember').checked

    if (!appCode || !url) {
        alert('请填写AppCode和URL')
        return
    }

    // 验证并格式化URL
    try {
        url = formatUrl(url)
    } catch (e) {
        alert(e.message)
        return
    }

    // 保存到localStorage
    if (remember) {
        localStorage.setItem('appCode', appCode)
        localStorage.setItem('url', url)
        localStorage.setItem('remember', 'true')
    } else {
        localStorage.removeItem('appCode')
        localStorage.removeItem('url')
        localStorage.setItem('remember', 'false')
    }

    // 发送导航请求到主进程
    ipcRenderer.send('navigate', { url, appCode })
}

function reload() {
    // 清空输入框
    document.getElementById('appCode').value = ''
    document.getElementById('url').value = ''
    
    // 清除保存的值
    localStorage.removeItem('appCode')
    localStorage.removeItem('url')
    
    // 重新加载页面
    window.location.reload()
} 